package org.example.homework.service.impl;


import org.example.homework.entity.User;
import org.example.homework.mapper.UserMapper;
import org.example.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.QTypeContributor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public void register(User user) {
        // 密码加密存储
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        System.out.println("添加用户信息为："+user);
        userMapper.insertUser(user);
    }

    @Override
    public User login(String identifier, String password) {
        // 尝试通过用户ID用户
        User user = userMapper.findById(Integer.parseInt(identifier));
        System.out.println("登入用户信息为："+user);
        // 验证密码
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }
//
    @Override
    public void changePassword(int userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
//        若返回 true，表示密码正确；false 则表示密码错误
        if (passwordEncoder.matches(oldPassword,  user.getPassword())) {
            userMapper.updatePassword(userId, passwordEncoder.encode(newPassword));
        } else {
            System.out.println(oldPassword);
            System.out.println(user.getPassword());
            throw new IllegalArgumentException("原密码错误");

        }
    }
    @Override
    public void deleteUser(int userId) {
        userMapper.deleteUser(userId);
    }

    @Override
    public List<User> getAllUsers() {
       userMapper.getAllUsers();
       return userMapper.getAllUsers();
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
}